#!/usr/bin/env groovy

import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelExec
import java.io.InputStream
import groovy.json.JsonSlurper

// 远程登录
// 创建JSch实例
def jsch = new JSch()

// 使用JSch建立到远程服务器的SSH会话
def session = jsch.getSession("root", "10.3.1.21", 22)

// 添加指定私钥路径的身份验证信息
jsch.addIdentity("/root/.ssh/id_rsa")

// 禁用主机密钥检查
session.setConfig("StrictHostKeyChecking", "no")

// 连接到远程服务器
session.connect()

// 要执行的远程命令
def command = "cat /opt/deploy/deployList.log"

// 打开一个执行通道
def channel = session.openChannel("exec")
(channel as ChannelExec).setCommand(command)
channel.connect()

// 从通道获取输入流
def inputStream = channel.inputStream

// 读取文件内容并存储在列表中
def lines = []
def reader = new BufferedReader(new InputStreamReader(inputStream))
String line
while ((line = reader.readLine()) != null) {
    lines.add(line)
}

// 关闭输入流，断开通道和会话连接
reader.close()
channel.disconnect()
session.disconnect()
// 返回文件内容的行列表
return lines

pipeline {
    agent {
      label "jenkinsNode-21"
    }
    environment {
        credentialsId = "0f305fa1-acba-4c0a-9bdf-cdd66f4ea128"
        replicas = 1
        imagePullPolicy = "IfNotPresent" //IfNotPresent
        k8sOpsDir = "/data/jenkins/cfhy-k8s"
        PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
    }
    parameters {
        choice(name: 'k8sNamespace', choices: ['prod'], description: '请选择k8s命名空间')
        choice(name: 'monitoringUpdate', choices: ['Y'], description: '第一个是否打开告警副本')
        choice(name: 'buildJob', choices: ['yes','no'], description: '选择是否关联deploy-item-111')
    }

    stages {
        stage('buildJob-deploy-item') {
            steps {
                script {
                    if ( "${params.buildJob}" == 'yes' ) {
                        // 将列表转换为JSON字符串并解析为Map对象
                        def listContent = new JsonSlurper().toJson(lines)
                        def deployList_map = new JsonSlurper().parseText(listContent)
						// 遍历 deployList_map 的键值对进行操作
						deployList_map.eachWithIndex { entry, index ->
						    def key = entry.key.tokenize('/').last().tokenize(':').first()
						    def value = entry.value
						    // 只有第一个打开告警副本
						    if ( "${index}" == 0 ) {
						    	def monitoringUpdate = "Y"
						    }  else {
							    def monitoringUpdate = "N"
							}
						    // 延迟4s传参并构建下游任务'deploy-item'，wait:false跳过等待直接执行下一个
	                        def buildjob = build job : 'deploy-item', quietPeriod : 4, wait : true , parameters:[string(name: "app_name" , value: "$key"),string(name: "dockerImageID" , value: "$value"),string(name: "monitoringUpdate" , value: "$monitoringUpdate")]
	                        //输出序号，app_name，dockerImageID
						    println "${index + 1}, app_name: $key, dockerImageID: $value, monitoringUpdate: $monitoringUpdate"
						}
					}
                }
            }
        }
    }
}